package com.chenxin.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import com.chenxin.common.annotation.InterfaceLogs;
import com.chenxin.common.core.text.Convert;
import com.chenxin.common.filter.PropertyPreExcludeFilter;
import com.chenxin.common.utils.ExceptionUtil;
import com.chenxin.common.utils.ServletUtils;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.framework.manager.AsyncManager;
import com.chenxin.framework.manager.factory.AsyncFactory;
import com.chenxin.system.domain.InterfaceLog;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 接口日志记录处理
 *
 * @author gry
 */
@Aspect
@Component
public class InterfaceLogAspect {
    private static final Logger log = LoggerFactory.getLogger(InterfaceLogAspect.class);
    /**
     * 排除敏感属性字段
     */
    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};
    /**
     * 计算操作消耗时间
     */
    private static final ThreadLocal<Long> TIME_COST_API = new NamedThreadLocal<Long>("Api Cost Time");

    /**
     * 处理请求前执行
     */
    @Before(value = "@annotation(controllerLog)")
    public void doBefore(JoinPoint joinPoint, InterfaceLogs controllerLog) {
        TIME_COST_API.set(System.currentTimeMillis());
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, InterfaceLogs controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, InterfaceLogs controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, InterfaceLogs controllerLog, final Exception e, Object jsonResult) {
        try {
            // *========WMS接口日志=========*//
            InterfaceLog interfaceLog = new InterfaceLog();
            // 如果业务异常
            if (e != null) {
                interfaceLog.setApiCode("500");
                interfaceLog.setApiMsg(StringUtils.substring(Convert.toStr(e.getMessage(), ExceptionUtil.getExceptionMessage(e)), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            interfaceLog.setApiProc(className + "." + methodName);

            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, interfaceLog, jsonResult);
            // 设置消耗时间
            interfaceLog.setCostTime(System.currentTimeMillis() - TIME_COST_API.get());
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordInterfaceLog(interfaceLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        } finally {
            TIME_COST_API.remove();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log    日志
     * @param apiLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, InterfaceLogs log, InterfaceLog apiLog, Object jsonResult) throws Exception {
        // 设置接口名称
        apiLog.setApiName(log.name());
        // 获取参数的信息，传入到数据库中。
        setRequestValue(joinPoint, apiLog, null);
        // 是否需要保存response，参数和值
        apiLog.setApiMsg(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param apiLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, InterfaceLog apiLog, String[] excludeParamNames) throws Exception {
        Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
        if (StringUtils.isEmpty(paramsMap)) {
            String params = argsArrayToString(joinPoint.getArgs());
            apiLog.setApiParam(StringUtils.substring(params, 0, 2000));
        } else {
            apiLog.setApiParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter(excludeParamNames)), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o)) {
                    try {
                        String jsonObj = JSON.toJSONString(o);
                        params += jsonObj + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 忽略敏感属性
     */
    public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames) {
        return new PropertyPreExcludeFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames));
    }
}